//
//  StatusOriginalViewPictureView.swift
//  sinaWeibo
//
//  Created by liii on 16/7/26.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit
import SDWebImage

// item 间距
private let picItemMargin: CGFloat = 5
// 重用标识
private let picCellReuseId = "picCellReuseId"

class StatusOriginalViewPictureView: UICollectionView {

    // 图片数组
    var imageURLs: [NSURL]? {
        didSet {
            // 根据图片数计算出配图View的size
            let imageSize = calculatePictureViewSize()
            // 更新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(imageSize)
            }
            testLabel.text = "\(imageURLs?.count ?? 0)"
            // 刷新界面(item重用)
            reloadData()
        }
    }
    
    init() {
        // 必须使用"流水布局"
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = picItemMargin
        layout.minimumLineSpacing = picItemMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        // 设置数据源
        self.dataSource = self
        self.delegate = self
        // 注册Cell
        self.registerClass(pictureCell.self, forCellWithReuseIdentifier: picCellReuseId)
        // 搭建UI界面
        setupUI()
        // 关闭滚动到顶部功能
        self.scrollsToTop = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func calculatePictureViewSize() -> CGSize {
        // 图片数量
        let imageCount = imageURLs?.count ?? 0
        
        let picWidth = screenWidth - 2 * StatusCellMargin
        
        // itemWidth
        let itemWidth = (picWidth - 2 * picItemMargin) / 3
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        // 没有配图
        if imageCount == 0 {
            return CGSizeZero
        }
        // 单图
        if imageCount == 1 {
            // 固定尺寸
            var imageSize = CGSizeMake(150, 100)
            let key = imageURLs?.first?.absoluteString ?? ""
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            let scale = UIScreen.mainScreen().scale
//            if image != nil {
            imageSize = CGSize(width: image.size.width * scale, height: image.size.height * scale)
//            }
            layout.itemSize = imageSize
            return imageSize
        }
        // 四图
        if imageCount == 4 {
            let picW = 2 * itemWidth + picItemMargin
            return CGSizeMake(picW, picW)
        }
        // 多图(1.求row, 2.再求rowWidth, 3.再求colHeight)
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let picHeight = row * itemWidth + (row - 1) * picItemMargin
        return CGSizeMake(picWidth,picHeight)
    }
    
    private func setupUI() {
        backgroundColor = UIColor(white: 0.90, alpha: 1)
        
        addSubview(testLabel)
        
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.center)
        }
    }
    
    private lazy var testLabel: UILabel = UIFactory.labelWithText("",  fontSize: 40, textColor: UIColor.redColor())
}

extension StatusOriginalViewPictureView: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(picCellReuseId, forIndexPath: indexPath) as! pictureCell
        
        cell.imageURL = imageURLs?[indexPath.row]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = imageURLs?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
    }
    
}

// SDPhotoBrowser的代理方法
extension StatusOriginalViewPictureView: SDPhotoBrowserDelegate {

    // 返回高清图片的URL
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        // 根据index, 在imageURLs数组中获取到url, 并获取urlString
        let urlString = imageURLs![index].absoluteString
        // 把urlString替换为高清图片的urlString
        let largeURLString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
        // 还原成URL返回
        return NSURL(string: largeURLString)
    }
    
    // 返回站位图片(原图片)
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        // 根据indexPath获取Cell
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        if let cell = cellForItemAtIndexPath(indexPath) as? pictureCell {
            // 获取Cell的图片
            return cell.picView.image
        }
        return nil
    }
    
}

class pictureCell: UICollectionViewCell {
    
    // 设置数据
    var imageURL: NSURL? {
        didSet {
            picView.sd_setImageWithURL(imageURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 搭建UI
    private func setupUI() {
        self.backgroundColor = UIColor.redColor()
        
        // 添加子控件
        contentView.addSubview(picView)
        
        // 布局子控件
        picView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    private lazy var picView: UIImageView = {
        let iv = UIImageView()
        /*
        ScaleToFill     // 缩放填充, 容易失真
        ScaleAspectFit  // 缩放部分适应(等比缩放), 容易留白
        ScaleAspectFill // 缩放部分填充(不留白), 会导致图片缺失, 但是效果最佳
        */
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
       return iv
    }()
}
